package com.example.courseapp.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.courseapp.BitmapUtils;
import com.example.courseapp.R;
import com.example.courseapp.RetrofitHelper;
import com.example.courseapp.bean.User;
import com.example.courseapp.net.CourseService;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class RegisterActivity extends AppCompatActivity {


    EditText userName, password, checkPassword, phone, age ,schoolTime;

    Button goLogin;


    String selectedOption, selectedText;


    CourseService courseService;

    User student;

    ImageView imageView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register);

        student = new User();

        courseService = RetrofitHelper.getInstance().createService(CourseService.class);

        userName = findViewById(R.id.user_name);

        password = findViewById(R.id.password);

        phone = findViewById(R.id.phone);

        age = findViewById(R.id.age);

        checkPassword = findViewById(R.id.check_password);





        imageView = findViewById(R.id.avatar);


        ActivityResultLauncher<Intent> register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == RESULT_OK) {
                    assert result.getData() != null;
                    UCrop.of(Objects.requireNonNull(result.getData().getData()), Uri.fromFile(new File(getCacheDir(),"SampleCropImage")))
                            .withAspectRatio(1f,1f)
                            .withMaxResultSize(512,512).start(RegisterActivity.this);
                }
            }
        });

        imageView.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            register.launch(intent);
        });


        goLogin = findViewById(R.id.go_login);




        goLogin.setOnClickListener(view -> {
            student.setUsername(userName.getText().toString());


            if (password.getText().toString().equals(checkPassword.getText().toString())) {
                student.setPassword(checkPassword.getText().toString());
                // 获取当前时间戳
                long timestamp = System.currentTimeMillis();

                // 创建 SimpleDateFormat 实例
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

                // 将时间戳转换为指定格式的字符串
                String formattedDate = dateFormat.format(new Date(timestamp));

                courseService.register(student).enqueue(new Callback<User>() {
                    @Override
                    public void onResponse(Call<User> call, Response<User> response) {
                        User newStu = response.body();

                      runOnUiThread(() -> {
                          //将参数带回到LoginActivity
                          Intent resultIntent = new Intent();
                          resultIntent.putExtra("userName", newStu.getUsername());

                          //设置返回结果码为 RESULT_OK
                          setResult(RESULT_OK, resultIntent);
                          //关闭当前 Activity
                          finish();
                      });
                    }

                    @Override
                    public void onFailure(Call<User> call, Throwable t) {
                        runOnUiThread(() -> {
                            Toast.makeText(RegisterActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                        });

                    }
                });

            } else {
                Toast.makeText(this, "两次密码不一致", Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            Uri resultUri = UCrop.getOutput(data);
            Bitmap bitmap = getBitmapFromUri(resultUri);

            student.setAvatar(BitmapUtils.bitmapToBase64(bitmap));
            Glide.with(imageView).load(bitmap)
                    .into(imageView);
        } else if (resultCode == UCrop.RESULT_ERROR) {
            UCrop.getError(data);
        }
    }

    private Bitmap getBitmapFromUri(Uri uri) {
        try {
            ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
            if (parcelFileDescriptor != null) {
                FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                return BitmapFactory.decodeFileDescriptor(fileDescriptor);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}